﻿@page "/setting/user"
@using AntDesign.TableModels
@inject IUserBasics iUserBasics
@inject IRoleBasics iRoleBasics
<Button OnClick="AddItem" Type="primary" Style="margin-bottom:16px">
    Add a user
</Button>
<Table @ref="table"
       TItem="SysUser"
       DataSource="@forecasts"
       Total="pagination.records"
       @bind-PageIndex="pagination.page"
       @bind-PageSize="pagination.rows"
       @bind-SelectedRows="selectedRows" ScrollX="1200" ScrollY="500" Loading="_loading" OnChange="HandleTableChange">
    @*<Selection Key="@(context.UserId.ToString())" />*@
    <Column @bind-Field="@context.UserName" />
    <Column @bind-Field="@context.UserLoginName" />
    <Column @bind-Field="@context.UserCreateTime" Format="yyyy-MM-dd" Sortable />
    <Column @bind-Field="@context.UserPwd" />
    <Column @bind-Field="@context.UserEmail" />
    <ActionColumn>
        <Space>
            <SpaceItem>
                <Button Type="@ButtonType.Link" Danger OnClick="_ => EditItem(context)">
                    Edit
                </Button>
            </SpaceItem>
        </Space>
        <Space>
            <SpaceItem><Button Danger OnClick="()=>Delete(context.UserId)">Delete</Button></SpaceItem>
        </Space>
    </ActionColumn>
</Table>
<Drawer Closable="true" Width="800" Visible="visible" Title=DrawerTitle OnClose="_=>closeDrawer()">
    <Template style="height:90%">
        <Form Model="@SysUsers"
              LabelColSpan="8"
              WrapperColSpan="16"
              OnFinish="OnFinish"
              Size="@AntSizeLDSType.Default">

            <FormItem Label="用户名">
                <Input @bind-Value="@context.UserName" />
            </FormItem>
            <FormItem Label="登录名">
                <Input @bind-Value="@context.UserLoginName" />
            </FormItem>
            <FormItem Label="登录密码">
                <Input @bind-Value="@context.UserPwd" />
            </FormItem>
            <FormItem Label="用户邮箱">
                <Input @bind-Value="@context.UserEmail" />
            </FormItem>
            <FormItem Label="用户说明">
                @*<Input @bind-Value="@context.UserParameter" />*@
                <TextArea @bind-Value="@context.UserParameter" MinRows="4" />
            </FormItem>
            <FormItem Label="用户角色">
                <Select @bind-Value="@context.RoelId"
                        TItemValue="int"
                        TItem="string"
                        Style="width: 200px; margin-bottom: 8px;"
                        Size="@_sizeValue">
                    <SelectOptions>
                        @foreach (var item in this.Role)
                        {
                            <SelectOption TItemValue="int" TItem="string" Value=item.RoleId Label=@item.RoleName />
                        }
                    </SelectOptions>
                </Select>
            </FormItem>


            <FormItem WrapperColOffset="8" WrapperColSpan="16">
                <Button HtmlType="submit">
                    Submit
                </Button>
            </FormItem>
        </Form>
    </Template>
</Drawer>

<style>
    .ant-form-item-label {
        flex: 0 0 130px !important;
    }

    .ant-col-offset-8 {
        margin-left: 130px;
    }


    .add-icon {
        border: 1px solid #abaaaa;
        color: #797777;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        text-align: center;
        line-height: 24px;
        margin-top: 4px;
        margin-left: 20px;
        padding-right: 1px;
        cursor: pointer;
    }
</style>


@code {
    WindowsHelper windows;
    bool _loading = false;
    string _selectedValue;
    private string _sizeValue = AntSizeLDSType.Default;
    List<SysUser> forecasts = new List<SysUser>();
    List<SysRole> Role = new List<SysRole>();
    IEnumerable<SysUser> selectedRows;
    ITable table;
    Core.DataAccess.Model.Pagination pagination = new Core.DataAccess.Model.Pagination
    {
        page = 1,
        rows = 2
    };
    bool visible = false;
    string DrawerTitle = "Add User";
    int selectRowId = 0;
    UserRegisterRequset SysUsers = new UserRegisterRequset
    {
    };
    void closeDrawer()
    {
        this.visible = false;
        this.DrawerTitle = "Add User";
        this.selectRowId = 0;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            windows = new WindowsHelper(jSRuntime);
            this.Role = await iRoleBasics.GetSysRoles(pagination);
            forecasts = await GetForecastAsync();
            var rolelist = await iRoleBasics.GetSysUserRoles();
            foreach (var item in forecasts)
            {
                item.RoelId = rolelist.Where(a => a.UserRoleUserId == item.UserId).FirstOrDefault().UserRoleRoleId;
            }

            await windows.HideLoadingAsync();
            await windows.SetTitleAsync("User");
            _ = InvokeAsync(StateHasChanged);
        }
    }
    public async Task<List<SysUser>> GetForecastAsync()
    {
        var result = await iUserBasics.GetSysUsers(pagination);

        return result;

    }
    private async Task HandleTableChange(QueryModel<SysUser> queryModel)
    {
        if (windows != null)
        {
            this.pagination.page = queryModel.PageIndex;
            this.pagination.rows = queryModel.PageSize;
            await this.LoadData();
        }
    }
    private async Task LoadData()
    {
        this._loading = true;
        await base.InvokeAsync(async () =>
        {
            forecasts = await GetForecastAsync();
            this._loading = false;
            base.StateHasChanged();
        });
    }

    public void RemoveSelection(int id)
    {
        var selected = selectedRows.Where(x => x.UserId != id);
        selectedRows = selected;
    }
    private async void OnFinish(EditContext editContext)
    {
        if (await this.DataValidation())
        {
            bool isSuccess = false;
            string merrorMessage = string.Empty;
            // submit
            await base.InvokeAsync(async () =>
            {
                if (selectRowId == 0)
                {
                    this.SysUsers.RoleKey = this.SysUsers.RoelId;
                    var result = await this.iUserBasics.RegisterAsync(this.SysUsers);
                    if (result.IsSuccessful)
                    {
                        isSuccess = true;
                        pagination.records++;
                    }
                    else
                    {
                        merrorMessage = result.Description;
                    }
                }
                else
                {
                    var requests = new UserModifyRequset() { UserId = this.SysUsers.UserId, UserName = this.SysUsers.UserName, UserLoginName = this.SysUsers.UserLoginName, UserPwd = this.SysUsers.UserPwd, UserEmail = this.SysUsers.UserEmail, UserParameter = this.SysUsers.UserParameter, RoleKey = this.SysUsers.RoelId };

                    var result = await this.iUserBasics.ModifyAsync(requests);
                    if (result.IsSuccessful)
                    {
                        isSuccess = true;
                        pagination.records++;
                    }
                    else
                    {
                        merrorMessage = result.Description;
                    }

                }

                if (isSuccess)
                {
                // 更新UI
                base.StateHasChanged();

                    var task = notice.Success(new NotificationConfig
                    {
                        Message = "保存成功"
                    });
                }
                else
                {
                    var task = notice.Error(new NotificationConfig
                    {
                        Message = "操作失败请重试",
                        Description = merrorMessage
                    });
                }
            });
        }


    }
    private async void Delete(int id)
    {
        var user = new UserDeleteRequest()
        {
            UserKey = id,
        };
        var result = await iUserBasics.DeleteAsync(user);
        if (result.IsSuccessful)
        {
            base.StateHasChanged();

            var task = notice.Success(new NotificationConfig
            {
                Message = "删除成功"
            });
        }
        else
        {
            var task = notice.Error(new NotificationConfig
            {
                Message = "操作失败请重试",
                Description = result.Description
            });
        }
    }

    void AddItem()
    {
        this.SysUsers = new UserRegisterRequset();
        this.DrawerTitle = "Add Route";
        this.selectRowId = 0;
        this.visible = true;
    }
    void EditItem(SysUser item)
    {
        this.SysUsers = new UserRegisterRequset() { UserId = item.UserId, UserName = item.UserName, UserLoginName = item.UserLoginName, UserPwd = item.UserPwd, UserEmail = item.UserEmail, UserParameter = item.UserParameter, RoelId = item.RoelId, RoleKey = item.RoelId };
        this.DrawerTitle = "Edit Route";
        this.selectRowId = item.UserId;
        this.visible = true;
    }

    private async Task<bool> DataValidation()
    {
        var message = new NotificationConfig
        {
            Message = "数据验证失败"
        };

        if (string.IsNullOrWhiteSpace(this.SysUsers.UserName))
        {
            message.Description = "请填写用户名";
        }
        if (string.IsNullOrWhiteSpace(this.SysUsers.UserLoginName))
        {
            message.Description = "请填写登录名";
        }
        if (string.IsNullOrWhiteSpace(this.SysUsers.UserPwd))
        {
            message.Description = "请输入登录密码";
        }
        if (this.SysUsers.RoelId <= 0)
        {
            message.Description = "请分配用户权限";
        }

        if (message.Description.Value != null)
        {
            await notice.Error(message);
            return false;
        }
        return true;
    }
}
